import { NextResponse } from 'next/server';

export interface ApiResponse<T = any> {
  success: boolean;
  code: number;
  data?: T;
  error?: string;
  message?: string;
}

// 添加CORS头的辅助函数
const addCorsHeaders = (response: NextResponse) => {
  response.headers.set('Access-Control-Allow-Origin', '*');
  response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
  response.headers.set('Access-Control-Allow-Credentials', 'true');
  return response;
};

// 成功响应
export const successResponse = <T = any>(data?: T, message?: string): NextResponse => {
  const response = NextResponse.json({
    success: true,
    code: 200,
    data,
    message
  } as ApiResponse<T>, { status: 200 });

  return addCorsHeaders(response);
};

// 错误响应 - 始终返回HTTP 200，但在响应体中包含错误code
export const errorResponse = (error: string, code: number = 400): NextResponse => {
  const response = NextResponse.json({
    success: false,
    code,
    error
  } as ApiResponse, { status: 200 }); // 始终返回HTTP 200

  return addCorsHeaders(response);
};

// 处理OPTIONS预检请求
export const optionsResponse = (): NextResponse => {
  const response = new NextResponse(null, { status: 200 });
  return addCorsHeaders(response);
}; 